<?php

class Antz_Cart
{
    protected $items = array();

    /**
     *  Add an item to the cart. $item is an array containing the title, id, price and quantity:
     *  $item = array(
     *      'title' => 'New wave ice cream',
     *      'id' => 4922,
     *      'price' => $4.95,
     *      'qty' => 3
     *  );
     *  ...Where the price is the total price for the customer including gst or other taxes/shipping costs
     */
    public function addItem($item){
        if(!is_array($item) || count($item)<4) return false;

        // find out if there is an identical item which we just update the quantity for
        $found = false;
        foreach($this->items as $k=>$v){
            if($v['id']==$item['id']){
                // bingo! we already have this item in our cart
                $this->items[$k]['qty'] += (int) $item['qty'];
                if($this->items[$k]['qty']<0) $this->items[$k]['qty'] = 0;
                $this->items[$k]['total_price'] = (float) $this->items[$k]['price'] * $this->items[$k]['qty'];
                $found = true;
            };
        };
        if(!$found){
            // we add the item to the cart
            $item['total_price'] = $item['price'] * $item['qty'];
            $this->items[] = $item;
        };
    }

    /**
     *  Allows us to overwrite the same registered item with new details. If the
     *  item does not exist already, this will add the item to the cart.
     */
    public function updateItem($item){
        if(!is_array($item) || count($item)<4) return false;

        $found = false;
        foreach($this->items as $k=>$v){
            if($v['id']==$item['id']){
                $found = true;
                $item['total_price'] = $item['price'] * $item['qty'];
                $this->items[$k] = $item;
            };
        };
    }

    /**
     *  Allows us to decrease the quantity of items for a given item
     */
    public function decreaseQuantity($itemId, $qty=1){
        foreach($this->items as $k=>$v){
            if($v['id']==$itemId) $this->items[$k]['qty'] = ($v['qty']-$qty);
        };
    }

    /**
     *  Allows us to remove an item from the cart completely
     */
    public function deleteItem($itemId){
        foreach($this->items as $k=>$v){
            if($v['id']==$itemId) unset($this->items[$k]);
        };
        $this->items = array_regenerate_keys($this->items);
    }

    /**
     *  Returns the array of arrays to provide all item details
     */
    public function getItemsAsArray(){
        return $this->items;
    }

    /**
     *  Cycles through the items in the cart and calculates the total cost value of the cart
     */
    public function getTotalPrice(){
        $total = 0;
        foreach($this->items as $k=>$v){
            $total += ($v['price']*$v['qty']);
        };
        return $total;
    }



}